package com.example.gulimall.ware.service.impl;

import com.example.common.constant.WareConstant;
import com.example.common.utils.R;
import com.example.gulimall.ware.entity.PurchaseDetailEntity;
import com.example.gulimall.ware.entity.WareSkuEntity;
import com.example.gulimall.ware.feign.ProductFeignService;
import com.example.gulimall.ware.service.PurchaseDetailService;
import com.example.gulimall.ware.service.WareSkuService;
import com.example.gulimall.ware.vo.PurchaseItemDone;
import com.example.gulimall.ware.vo.MergeVo;
import com.example.gulimall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.ware.dao.PurchaseDao;
import com.example.gulimall.ware.entity.PurchaseEntity;
import com.example.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseService purchaseService;
    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;
    @Autowired
    ProductFeignService productFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);

    }

    @Transactional
    @Override
    public R saveMerge(MergeVo mergeVo) {
        //如果不选择合并到那个采购单则新建一个采购单，选择了就合并到选择的采购单
        //只能合并采购状态为0或者1的,因为已经领取或者完成或者异常应该是不能再合并了，状态也不能改变
        PurchaseEntity reslut=this.getById(mergeVo.getPurchaseId());
        if (reslut!=null){
            if (reslut.getStatus()!=0&&reslut.getStatus()!=1){
                //主动报错，让事物回滚
               return R.error(1,"只能给新建或者已分配的采购单合并");
            }
        }


        if (mergeVo!=null){
            if (mergeVo.getPurchaseId()==null){
                //创建采购单
                PurchaseEntity purchaseEntity=new PurchaseEntity();
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
                purchaseEntity.setCreateTime(new Date());
                purchaseEntity.setUpdateTime(new Date());
                this.save(purchaseEntity);
                mergeVo.setPurchaseId(purchaseEntity.getId());
            }


            //合并采购单,实际就是就采购需求设置到采购订单
            List<Long> items=mergeVo.getItems();
         List<PurchaseDetailEntity> collect= items.stream().map(i->{
               PurchaseDetailEntity purchaseDetailEntity=new PurchaseDetailEntity();
               purchaseDetailEntity.setId(i);
               purchaseDetailEntity.setPurchaseId(mergeVo.getPurchaseId());
               purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
               return purchaseDetailEntity;
           }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
            PurchaseEntity purchaseEntity=new PurchaseEntity();
            //更新采购订单时间
            purchaseEntity.setId(mergeVo.getPurchaseId());
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);

        }
    return R.ok();
    }
    @Transactional
    @Override
    public R purchaseReceived(List<Long> ids) {
        //1、确认当前采购单是新建或者已分配状态
       List<PurchaseEntity> purchaseEntities=  ids.stream().map(i->{
             PurchaseEntity purchaseEntity=new PurchaseEntity();
             purchaseEntity=this.getById(i);
             return purchaseEntity;
         }).filter(item->{ //数据过滤器 true的数据返回 false不返回
             if (item.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()||item.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
                    return  true;
             }
             return false;
       }).map(item->{ //设置领取状态和领取时间一起返回出去
           item.setUpdateTime(new Date());
           item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
           return  item;
       }).collect(Collectors.toList());
       if (purchaseEntities.size()==0||purchaseEntities==null){
           //2、改变采购单的状态
          return  R.error(1,"只能领取新建和已分配的采购单");
       }
        this.updateBatchById(purchaseEntities);

        //3、改变采购项的状态
        for (Long id:ids) {
            //查询采购需求集合
            List<PurchaseDetailEntity> list=purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>()
            .eq("purchase_id",id));
            if (list==null||list.size()==0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

                return R.error(1,"该采购单没有采购需求，不能领取");
            }
           list= list.stream().map(item->{

                item.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return item;
            }).collect(Collectors.toList());
           purchaseDetailService.updateBatchById(list);

        }
        return R.ok();
    }

    /**
     *
     * @param vos
     * 采购时由于一个采购单有多个采购需求，可能某个采购需求因为采购不足或者其他原因采购异常，因此采购项完成添加一个
     * 由于前期
     */
    @Transactional
    @Override
    public void purchaseDone(PurchaseDoneVo vos) {
           //1、改变采购项的状态
        boolean isFlag=true; //记录采购是否成功 ，成功为true,失败false
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDone item:vos.getItems()) {
            PurchaseDetailEntity detailEntity=new PurchaseDetailEntity();
            //如果采购失败，则不要入库，成功入库
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
               isFlag=false;
                detailEntity.setReason(item.getReason()); //设置采购失败原因
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());//设置采购失败
            }else {
                //采购成功，设置状态
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                ////2、将成功采购的进行入库

                //查询该商品库存里面是否已经存在，如果有则update 没有insert
                   //detailEntity 根据id查询采购需求，获得商品id和仓库id
                     PurchaseDetailEntity purchaseDetailEntity=purchaseDetailService.getById(item.getItemId());

                         WareSkuEntity  wareSkuEntity= wareSkuService.getOne(new QueryWrapper<WareSkuEntity>()
                        .eq("sku_id",purchaseDetailEntity.getSkuId()).eq("ware_id",purchaseDetailEntity.getWareId()));

               if (wareSkuEntity!=null){
                   //有值表示仓库已有该商品执行update
                   wareSkuEntity.setStock(wareSkuEntity.getStock()+purchaseDetailEntity.getSkuNum());

                   //根据id修改
                   wareSkuService.updateById(wareSkuEntity);
               }else {
                   WareSkuEntity wareSkuEntity1=new WareSkuEntity();
                   //没有，表示仓库中没有该商品insert
                   wareSkuEntity1.setSkuId(purchaseDetailEntity.getSkuId());
                   wareSkuEntity1.setWareId(purchaseDetailEntity.getWareId());
                   wareSkuEntity1.setStock(purchaseDetailEntity.getSkuNum());
                   wareSkuEntity1.setStockLocked(0);
                   //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
                   //1、自己catch异常
                   //TODO 还可以用什么办法让异常出现以后不回滚？高级
                   try {
                       R info= productFeignService.info(wareSkuEntity1.getSkuId());
                       Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                       if(info.getCode() == 0){
                           wareSkuEntity1.setSkuName((String) data.get("skuName"));
                       }
                   }catch (Exception e){

                }
                   wareSkuService.save(wareSkuEntity1);
               }

            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        //改变采购项
        purchaseDetailService.updateBatchById(updates);
        //3、改变采购单状态
        PurchaseEntity purchaseEntity=new PurchaseEntity();
        purchaseEntity.setId(vos.getId());
        purchaseEntity.setUpdateTime(new Date());
        if (isFlag){
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        }else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        this.updateById(purchaseEntity);

    }

}